import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'
import { printFile } from '@/utils/print'
import { Message } from 'element-ui'

export const downloadPDF = page => {
  html2canvas(page, { scale: 10, useCORS: true }).then((canvas) => {
    canvas2PDF(canvas);
  });
}

const canvas2PDF = canvas => {
  const contentWidth = canvas.width
  const contentHeight = canvas.height

  const margin = 30;
  // a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
  const imgWidth = 595.28 - 2 * margin
  const imgHeight = (imgWidth / contentWidth) * contentHeight
  // 左右各保留30px的间距
  // 第一个参数： l：横向  p：纵向
  // 第二个参数：测量单位（"pt"，"mm", "cm", "m", "in" or "px"）
  const pdf = new JsPDF('p', 'pt')
  // x 坐标设置为 margin 以确保左右各有30px的间距
  const x = margin;
  const y = 0; // y 坐标可以根据需要调整
  pdf.addImage(
    canvas.toDataURL('image/png', 1.0),
    'PNG',
    x,
    y,
    imgWidth,
    imgHeight,
    undefined,
    'MEDIUM', // 这里可以调整图像质量，如 'FAST'、'SLOW' 或 'MEDIUM'
  )

  // pdf.save("file.pdf");  // 导出
  const pdfData = pdf.output('datauristring')
  const link = window.URL.createObjectURL(base64ToBlob(pdfData))
  console.log(link)
  const file = blobToFile(base64ToBlob(pdfData), 'file.pdf');
  printFile(
    file,
    () => {
      Message({ message: '打印成功', type: 'success', duration: 2 * 1000 })
    },
    (err) => {
      Message({ message: err, type: 'error', duration: 5 * 1000 })
    },
    () => {
      Message({ message: '打印机为空', type: 'error', duration: 5 * 1000 })
    }
  )
}

const base64ToBlob = (dataUrl) => {
  const arr = dataUrl.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}

// blob转换为file
const blobToFile = (theBlob, fileName) => {
  theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
  theBlob.name = fileName; // 文件名
  return new File([theBlob], fileName, { type: theBlob.type, lastModified: Date.now() });
};
